<?php
/**
 * Lvl_Api
 * Класс Lvl_Api отвечает за работу с API level.travel 
 * @author Sayp
 */
class Lvl_Api {
	
	/**
	 * Делаем запрос к API level.travel
	 * @param string $url - url, на который слать запрос
	 * @param array $arrParams - массив параметров
	 * @return mixed
	 */
	private function request($url, array $arrParams = array()) {
// 		$opts = array(
// 			'http'=>array(
// 				'method'=>"GET",
// 				'header'=>'Authorization: Token token="42582fa63a4879bc2b856fcf7447e718"'
// 			)
// 		);
// 		$context = stream_context_create($opts);
		$arrParams['key'] = '950f96d0bf71a2cb3b44ca9e8f5d3272';
		$arrParams['api_version'] = '2';
 		$url .= '?' . http_build_query($arrParams);
		
		$result = file_get_contents($url);
		return json_decode($result, 1);
	}
	
	public function getCountryPrice($iso, $night = 7) {
		$month = intval(date('m', time()));
		
		$arrParams = array(
			'country_to' => $iso,
			'city_from' => 'Moscow',
			'start_month' => $month,
			'start_year' => intval(date('Y', time()))
		);
		$arrPrices = $this->request('https://level.travel/papi/references/monthly_stats', $arrParams);
		
		if (is_array($arrPrices['response'])) {
			foreach ($arrPrices['response'] as $arrPrice) {
				if ($arrPrice['month'] != $month) continue;
				
				foreach ($arrPrice['stats'] as $arrStat) {
					if ($arrStat['nights'] != $night) continue;
					
					return $arrStat['min_price'];
				}
			}
		}
		
		return null;
	}
	
	/**
	 * Парсим страны level.travel и обновляем их в БД
	 */
	public function parseCountries() {
		$arrCountries = $this->request('https://level.travel/papi/references/countries');

		$objDB = Service_Database::instance();
		foreach ($arrCountries as $arrCountry) {
			$objDB->insert('lvl_country', array(
				'ID_lvl_country' => $arrCountry['id'],
				'country_name_ru' => $arrCountry['name_ru'],
				'country_name_en' => $arrCountry['name_en'],
				'iso' => strtolower($arrCountry['iso2']),
				'active' => $arrCountry['active'],
				'searchable' => $arrCountry['searchable']
			), 'update');
		}
	}
	
	/**
	 * Парсим города level.travel и обновляем их в БД
	 */
	public function parseCities() {
		$arrCities = $this->request('https://level.travel/papi/references/cities');

		$objDB = Service_Database::instance();
		foreach ($arrCities as $arrCity) {
			$objDB->insert('lvl_city', array(
				'ID_lvl_city' => $arrCity['id'],
				'city_name_ru' => Service_Escape::absolutelyEscapeString($arrCity['name_ru']),
				'city_name_en' => Service_Escape::absolutelyEscapeString($arrCity['name_en']),
				'iata' => strtolower($arrCity['iata']),
				'active' => $arrCity['active'],
				'featured' => $arrCity['featured'],
				'ID_lvl_country' => $arrCity['country']['id']
			), 'update');
		}
	}
	
	/**
	 * Получаем отели с турами
	 */
	public function parseTours($toCountry, $startDate) {
		$objDB = Service_Database::instance();
		$arrCountries = $objDB->select('SELECT `ID_lvl_country`, `iso`, `country_name_ru` FROM `lvl_country`');
		$arrCountries = Service_ArrayConverter::makeKeyFromColumn($arrCountries, 'country_name_ru');

		$arrParams = array(
			'from_city' => 'Moscow',
			'from_country' => 'ru',
			'to_country' => $toCountry,
			'nights' => 7,
			'adults' => 2,
			'start_date' => $startDate
		);
		
		$arrTours = $this->request('https://level.travel/papi/search/perform', $arrParams);
		if (empty($arrTours['response'])) return;

		$parseDate = Service_Date::gLocalTime2BD();
		foreach ($arrTours['response'] as $arrTour) {
			$arrInsert = array(
				'stars' => $arrTour['hotel']['stars'],
				'hotel_name' => Service_Escape::absolutelyEscapeString($arrTour['hotel']['name']),
				'description' => Service_Escape::absolutelyEscapeString($arrTour['hotel']['desc']),
				'link' => $arrTour['hotel']['link'],
				'stars' => $arrTour['hotel']['stars'],
				'city_name_ru' => $arrTour['hotel']['city'],
				'country_name_ru' => $arrTour['hotel']['country'],
				'min_price' => $arrTour['min_price'],
				'max_price' => $arrTour['max_price'],
				'created_at' => $parseDate
			);
			
			if (isset($arrTour['hotel']['image']['preview'])) $arrInsert['img_preview'] = $arrTour['hotel']['image']['preview'];
			if (isset($arrTour['hotel']['image']['full_size'])) $arrInsert['img_full_size'] = $arrTour['hotel']['image']['full_size'];
			
			$countryName = $arrTour['hotel']['country'];
			if (isset($arrCountries[$countryName])) {
				$arrInsert['ID_lvl_country'] = $arrCountries[$countryName]['ID_lvl_country'];
				$arrInsert['iso'] = $arrCountries[$countryName]['iso'];
			}
			
			$objDB->insert('lvl_tour', $arrInsert);
		}
		
	}
	
}